<template>
  <div class="app-container">
    <el-form  class="query-wrapper" :model="queryParams" inline>
      <el-form-item prop="name">
        <el-input v-model="queryParams.name" clearable style="width:200px" placeholder="Name" />
      </el-form-item>
      <el-form-item>
      
        <el-button type="primary" icon="search" @click="search">{{
          $t("ship.button.search")
          }}</el-button>
        <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
        <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
        <el-button type="primary"  plain icon="Plus" @click="addClickEvent"   v-hasPermi="['template:edit']">
          {{ $t("ship.button.plus") }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>

  <el-table stripe class="daf-table" :data="listData" style="width: 100%" @sort-change="handleSortChange">
    <!-- <el-table-column prop="portId" label="Port No" width="120" /> -->
    <el-table-column prop="id" label="ID" width="120" align="center" /> 
 
    <el-table-column prop="name" label="Name" />
    <el-table-column prop="url" label="URL" />
    <el-table-column label="Operation" width="200" align="center" >
      <template #default="scope">
        <span class="btn-primary" @click="editClickEvent(scope.row)">{{ $t("ship.button.edit") }}</span
          >&nbsp;&nbsp;
        <span class="btn-primary" @click="downloadClickEvent(scope.row)">{{
          $t("ship.button.download")
          }}</span>
      </template>
    </el-table-column>
  </el-table>

  <pagination v-show="total > 0" :total="total" :page="queryParams.pageNum" :limit="queryParams.pageSize"
    @pagination="pageQuery" style="float: right" />

  <el-dialog :width="800" destroy-on-close draggable :title="dialogTitle" v-model="dialogFormVisible">
    <el-form :model="formParam" :rules="rules" ref="custForm">
      <el-row>
        <el-col :span="24">
          <el-form-item label="Name" label-width="120px" prop="name">
            <el-input v-model="formParam.name"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="24">
          <el-form-item label="URL" label-width="120px" prop="url">
            <el-input  v-model="formParam.url"></el-input>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row>
        <el-col :span="24">
      <el-form-item label="Template File" prop="">
        <el-button type="primary" size="small" style="margin: 10px" onclick="this.nextSibling.click()">
          {{ $t("ship.button.upload") }}</el-button>
        <input type="file" id="upload-file" v-show="false"
          @change="uploadFile($event)" accept=".xlsx,.xls" />
        <a href="javascript:void(0)" @click="downloadPDF(formParam.url)">{{
          formParam.file?.name || getFileName(formParam.url)
          }}</a>
      </el-form-item>
    </el-col>
  </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("ship.button.cancel")
          }}</el-button>
        <el-button @click="resetForm" type="warning">{{
          $t("ship.button.reset")
          }}</el-button>
        <el-button type="primary" @click="submitForm">{{
          $t("ship.button.submit")
          }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup name="template">
  import { ref, onMounted, reactive } from "vue"; 
  import service from "@/utils/request"; 
  import { ElNotification, ElMessageBox } from "element-plus";
  import { downloadFile } from "@/utils/downloadFile";
  import {convertUrl} from "@/utils/tencentCos";

  const custForm = ref(null);
  const dialogTitle = ref("");
  const initForm = {
    id: null,
    name: null,
    url: null,
    file: null,
    remark: null
  };
  const formParam = reactive(Object.assign({}, initForm));

  const total = ref(0);

  const rules = ref({
    name: [{ required: true, message: " Name is required", trigger: "blur" }],
    url: [{ required: true, message: "URL is required", trigger: "blur" }],
  });

  const queryParams = reactive({
    pageNum: 1,
    pageSize: 20,
    name: null,
    orderByColumn: undefined,
    isAsc: undefined,
  });

  const listData = ref([])
 

  const refreshTable = async () => {
   let result =await service.get("/shipping/template/list",{ params: queryParams })
    listData.value = result.data; 
  };
  const resetQuery = (data) => {
    Object.assign(queryParams, data)
    refreshTable()
  }
  const dialogFormVisible = ref(false);

  const editClickEvent = (row: any) => {
    dialogTitle.value = "Update template";
    dialogFormVisible.value = true;
    isAdd = false;
    Object.keys(initForm).forEach((k) => (formParam[k] = row[k]));
  };

  let isAdd = false;

  const addClickEvent = () => {
    dialogTitle.value = "Add Template";
    isAdd = true;
    dialogFormVisible.value = true;
    Object.assign(formParam, initForm);
  };

  const resetForm = () => {
    // @ts-ignore
    custForm.value.resetFields();
  };

  const submitForm = () => {
    const formData = new FormData()
    for (const [k, n] of Object.entries(formParam)) {
      if (n) {
        formData.append(k, n)
      }
    }
    // @ts-ignore
    custForm.value.validate(async (valid) => {
      service[isAdd?"post":"put"]('/shipping/template',formData).then(response => { 
           // @ts-ignore
          ElNotification.success({ title: "Prompt information", message: "save successful!", position: "bottom-right" });
          dialogFormVisible.value = false;
          refreshTable();
         });
    });
  };

  const pageQuery = async (e) => {
    queryParams.pageNum = e.page;
    queryParams.pageSize = e.limit;

  };

  const search = () => {
    refreshTable()
  };

  const handleSortChange = async (column: any) => {

  };
  // 获取文件名称
  function getFileName(name) {
        if (name == null) {
            return name;
        }
        // 如果是url那么取最后的名字 如果不是直接返回
        if (name.lastIndexOf("/") > -1) {
            return name.slice(name.lastIndexOf("/") + 1);
        } else {
            return name;
        }
    }
  const downloadClickEvent = (row) => {
    if(row.url.indexOf('/template')==0){
      downloadPDF(row.url)
    }else{
      if(row.id !=5){
      downloadFile(row.url, queryParams, row.name + '.xlsx');
    }else{
      downloadFile(row.url, queryParams, row.name + '.docx');
    } 
    }
   
  };
  function downloadPDF(url) {
        if (!url) return
        ElMessageBox.confirm("Confirm to Download the file？", "Download  Information", {
            type: "warning",
            confirmButtonText: "Confirm",
            cancelButtonText: "Cancel",
        }).then(async () => {
          
            const newUrl = convertUrl(url);
            const a = document.createElement('a');
            a.href = newUrl;
            a.download = getFileName(newUrl);
            a.click();

        });
    }
const uploadFile = async (event, key) => {
    if (event.target == null || event.target.files[0] == null) {
      return;
    }
    const urlFile = document.querySelector("#upload-file");
    formParam.file = urlFile.files[0];
  };

  onMounted(async () => {
     refreshTable();
  });
</script>
<style>

</style>